<template>
  <el-tooltip content="上传附件" placement="bottom">
    <el-button type="text" @click="openAttachmentDialog">
      <el-icon><Document /></el-icon>
    </el-button>
  </el-tooltip>
</template>

<script setup lang="ts">
import { ElButton, ElTooltip, ElIcon, ElMessage } from 'element-plus';
import { Document } from '@element-plus/icons-vue';
import { ref, inject } from 'vue';
import { addImage01 } from "@/api/common/work/SelectWork.js";

const editor = inject('editor') as any;

const openAttachmentDialog = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '*'; // 你可以指定接受的文件类型，例如 'application/pdf'
  input.onchange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files.length > 0) {
      const file = target.files[0];
      try {
        const formData = new FormData();
        formData.append('file', file);
        const response = await addImage01(formData);
        if (response && response.code === 200 && response.data && response.data.data && response.data.data.length > 0) {
          const attachmentUrl = response.data.data[0].url;
          if (editor) {
            editor.insertHTML(`<a href="${attachmentUrl}" target="_blank">${file.name}</a>`);
          }
        } else {
          console.error('附件上传失败:', response);
          ElMessage.error('附件上传失败');
        }
      } catch (error) {
        ElMessage.error('附件上传错误:', error);
      }
    }
  };
  input.click();
};
</script>